package com.fenrirtec.aepp.portal.api;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fenrirtec.aepp.common.dto.AttachmentDto;
import com.fenrirtec.aepp.common.dto.AuditFlowDto;
import com.fenrirtec.aepp.common.dto.MemberDto;
import com.fenrirtec.aepp.common.dto.SystemConfigDto;
import com.fenrirtec.aepp.common.service.AttachmentService;
import com.fenrirtec.aepp.common.service.FileService;
import com.fenrirtec.aepp.common.service.MemberManageService;
import com.fenrirtec.aepp.common.service.impl.AttachmentServiceImpl;
import com.fenrirtec.aepp.common.service.impl.FileServiceImpl;
import com.fenrirtec.aepp.common.service.impl.MemberManageServiceImpl;
import com.fenrirtec.aepp.common.support.JSONActionSupport;
import com.fenrirtec.core.definition.BaseDefinition.API;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;

public class MaterialUploadAPI extends JSONActionSupport {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(MaterialUploadAPI.class);

	public MaterialUploadAPI() {
	}
	
	private String param;

	public String getParam() {
		return this.param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	@Override
	protected List<ErrorInfo> doValidate() {
		return null;
	}

	@Override
	protected JSONObject doExecute() {
		AttachmentService attachmentService = new AttachmentServiceImpl();
		FileService fileService = new FileServiceImpl();
		MemberManageService memberService = new MemberManageServiceImpl();
		SystemConfigDto config = getSystemConfig();
		
		try {
			JSONObject jsonObj = JSONObject.parseObject(this.param);
			
			Integer attachmentCategory = 0;
			String memberLoginName = jsonObj.getString("member_login_name");
			
			JSONObject uploadData = jsonObj.getJSONObject("upload");
			JSONObject imageData = jsonObj.getJSONObject("image");
			
			if (imageData != null && !imageData.isEmpty()) {
				Iterator<?> it = imageData.keySet().iterator();
				while (it.hasNext()) {
					String key = (String) it.next();
					JSONObject imageInfo = imageData.getJSONObject(key);
					
					if (imageInfo != null && !imageInfo.isEmpty()) {
						Integer attachmentId = imageInfo.getInteger("attachment_id");
						Boolean deleteFlag = imageInfo.getBoolean("delete_flag");
						if (attachmentId > 0 && deleteFlag != null && deleteFlag) {
							AttachmentDto attachmentDto = attachmentService.searchAttachment(attachmentId);
							attachmentService.removeAttachment(attachmentId);
							fileService.deleteFile(attachmentDto.getPath());
							
							if (StringUtils.isNotEmpty(memberLoginName)) {
								if (key.equals("image_contact_front")) {
									attachmentCategory = 1;
								} else if (key.equals("image_contact_back")) {
									attachmentCategory = 2;
								} else if (key.equals("image_license")) {
									attachmentCategory = 3;
								} else if (key.equals("image_legal_front")) {
									attachmentCategory = 4;
								} else if (key.equals("image_legal_back")) {
									attachmentCategory = 5;
								}
								memberService.removeImage(memberLoginName, attachmentCategory, attachmentId);
							}
						}
					}
				}
			}
			
			if (uploadData != null && !uploadData.isEmpty()) {
				Iterator<?> it = uploadData.keySet().iterator();
				while (it.hasNext()) {
					String key = (String) it.next();
					JSONObject uploadInfo = uploadData.getJSONObject(key);
					if (uploadInfo != null && !uploadInfo.isEmpty()) {
						Integer uploadId = uploadInfo.getInteger("upload_id");
						Integer uploadFileType = uploadInfo.getInteger("upload_file_type");
						String uploadFilePath = uploadInfo.getString("upload_file_path");
						String uploadPerson = uploadInfo.getString("upload_person");
						String path = "";
						String rootPath = config.getUploadRootFolder();
						String savePath = config.getQualificationsSaveFolder();
						File saveFolder = new File(rootPath, savePath);
						if (!saveFolder.exists()) {
							saveFolder.mkdirs();
						}
						String fileName = uploadFilePath.substring(uploadFilePath.lastIndexOf("/") + 1);
						path = new File(saveFolder, fileName).getAbsolutePath();
						Integer attachmentId = attachmentService.saveAttachment(uploadFileType, path, "", uploadPerson);
						attachmentService.relateMemberMaterial(memberLoginName, key.replace("image_", "upload_"), attachmentId);
						fileService.moveFile(uploadFilePath, path);
						attachmentService.removeUpload(uploadId);
						fileService.deleteFile(uploadFilePath);
					}
				}
			}
			
			MemberDto memberDto = memberService.memberInfo(memberLoginName);
			Integer imgContactFront = memberDto.getImageContactCertificatesFront();
			Integer imgContactBack = memberDto.getImageContactCertificatesBack();
			Integer imgLicense = memberDto.getImageLicense();
			if (imgContactFront != null && imgContactFront > 0 && imgContactBack != null && imgContactBack > 0 && imgLicense != null && imgLicense > 0) {
				AuditFlowDto auditFlowDto = new AuditFlowDto();
				auditFlowDto.setMemberLoginName(memberLoginName);
				auditFlowDto.setAuditSequence(memberDto.getLastestAuditSequence());
				auditFlowDto.setAuditPhase(memberDto.getLastestAuditPhase());
				if (memberDto.getLastestAuditPhase() == 3 && memberDto.getLastestAuditResult() == 1) {
					auditFlowDto.setAuditResult(9);
					auditFlowDto.setAuditComment("");
				} else if (memberDto.getLastestAuditPhase() == 4 && memberDto.getLastestAuditResult() == 2) {
					auditFlowDto.setAuditResult(1);
					auditFlowDto.setAuditComment(memberDto.getLastestAuditComment());
				}
				auditFlowDto.setLoginName(memberLoginName);
				auditFlowDto.setUpdateUser(memberLoginName);
				memberService.updateAuditResult(auditFlowDto);
				
				if (memberDto.getLastestAuditPhase() == 3 && memberDto.getLastestAuditResult() == 1) {
					auditFlowDto.setAuditSequence(memberDto.getLastestAuditSequence() + 1);
					auditFlowDto.setAuditPhase(4);
					auditFlowDto.setAuditResult(1);
					memberService.insertAuditFlow(auditFlowDto);
				}
			}
			
		} catch (DatabaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error("database error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (UnexpectedException e) {
			if (logger.isErrorEnabled()) {
				logger.error("unexpected error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		}

		JSONObject root = new JSONObject();
		root.put(API.Common.Response.STATUS, API.Common.Status.SUCCESS);
		return root;
	}
}
